package com.acme.ioniolab.transportfile.implementation;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.acme.ioniolab.transportfile.Server;

public class IOServer implements Server {

	@Override
	public long receiveFile(String fileName, int port) throws IOException {
		long time = 0;
		try (ServerSocket serverSocket = new ServerSocket(port);
				Socket socket = serverSocket.accept();
				DataInputStream inputStream = new DataInputStream(socket.getInputStream());
				FileOutputStream outputStream = new FileOutputStream(fileName)) {
			byte[] buffer = new byte[1024];
			int bytesRead = 0;
			time = System.currentTimeMillis();
			long fileSize = inputStream.readLong();
			long totalBytesRead = 0;
			while ((bytesRead = inputStream.read(buffer)) != -1 && totalBytesRead < fileSize) {
				outputStream.write(buffer, 0, bytesRead);
				totalBytesRead += bytesRead;
			} 
			time = System.currentTimeMillis() - time;
		}
		return time;
	}

}
